package com.hanson.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hanson.Const;
import com.hanson.common.bean.*;
import com.hanson.common.exception.BusinessException;
import com.hanson.common.service.RedisService;
import com.hanson.common.util.BusinessUtil;
import com.hanson.entity.*;
import com.hanson.mapper.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderService {
    @Autowired
    private OrderBeanMapper orderBeanMapper;
    @Autowired
    private GoodsAttrValueBeanMapper goodsAttrValueBeanMapper;
    @Autowired
    private GoodsBeanMapper goodsBeanMapper;
    @Autowired
    private CartBeanMapper cartBeanMapper;
    @Autowired
    private UserAddresBeanMapper userAddresBeanMapper;
    @Autowired
    private UserBeanMapper userBeanMapper;
    @Autowired
    private SeckillGoodsBeanMapper seckillGoodsBeanMapper;
    @Autowired
    private GroupGoodsBeanMapper groupGoodsBeanMapper;
    @Autowired
    private ScoreSeqBeanMapper scoreSeqBeanMapper;
    @Autowired
    private AcctbkSeqBeanMapper acctbkSeqBeanMapper;
    @Autowired
    private SpreadInfoBeanMapper spreadInfoBeanMapper;
    @Autowired
    private RedisService redisService;
    @Autowired
    private PayService payService;
    @Autowired
    private SmsService smsService;

    public void finishOrder(String orderId) {
        List<OrderBean> orderBeanList = orderBeanMapper.selectByOrderId(orderId);
        if (CollectionUtils.isNotEmpty(orderBeanList)) {
            this.updateStatus(5, orderId);
            OrderBean orderBean = orderBeanList.get(0);
            GoodsBean goodsBean = goodsBeanMapper.selectByPrimaryKey(orderBean.getGoodsId());
            UserBean userBean = userBeanMapper.selectByOpenId(orderBean.getOpenId());
            log.info("【开始计算积分 佣金 score= {},spreadMoney = {}】", goodsBean.getScore(), goodsBean.getSpreadMoney());
            //计算积分和佣金
            if (null != goodsBean && null != userBean) {
                if (goodsBean.getScore() != null && goodsBean.getScore() != 0) {
                    userBean.setScore(userBean.getScore() + goodsBean.getScore());
                    ScoreSeqBean scoreSeqBean = new ScoreSeqBean();
                    scoreSeqBean.setCreateDate(new Date());
                    scoreSeqBean.setOpenId(userBean.getOpenId());
                    scoreSeqBean.setRemark("购买商品赠送积分");
                    scoreSeqBean.setScore(goodsBean.getScore());
                    scoreSeqBean.setType(1);
                    scoreSeqBeanMapper.insert(scoreSeqBean);
                    userBeanMapper.updateByPrimaryKeySelective(userBean);
                    redisService.del(String.format(Const.USER_REDIS_KEY, userBean.getOpenId()));
                }
                int spreadMoney = goodsBean.getSpreadMoney() == null ? 0 : goodsBean.getSpreadMoney();
                int speadChildMoney = goodsBean.getSpreadChildMoney() == null ? 0 : goodsBean.getSpreadChildMoney();
                if (!(spreadMoney == 0 && speadChildMoney == 0)) {
                    String key = String.format(Const.SHARE_GOODS_KEY, goodsBean.getId());
                    Object parentIdObj = redisService.hget(key, orderBean.getOpenId());
                    if (null == parentIdObj) {
                        List<SpreadInfoBean> childIds = spreadInfoBeanMapper.selectByChildId(userBean.getOpenId());
                        if (CollectionUtils.isNotEmpty(childIds)) {
                            //代理商下级购买计算佣金
                            SpreadInfoBean spreadInfoBean = childIds.get(0);
                            int spreadLevel = spreadInfoBean.getLevel();
                            if(spreadLevel <= 3){
                                UserBean parentBean = userBeanMapper.selectByOpenId(spreadInfoBean.getParentId());
                                if(null != parentBean){
                                    int addMoney = 0;
                                    if(spreadLevel == 2){
                                        addMoney = spreadMoney;
                                    }else if(spreadLevel == 3){
                                        addMoney = speadChildMoney;
                                    }
                                    if(addMoney > 0){
                                        parentBean.setMoney(parentBean.getMoney() + addMoney);
                                        userBeanMapper.updateByPrimaryKeySelective(parentBean);
                                        redisService.del(String.format(Const.USER_REDIS_KEY, parentBean.getOpenId()));

                                        AcctbkSeqBean acctbkSeqBean = new AcctbkSeqBean();
                                        acctbkSeqBean.setChildId(userBean.getOpenId());
                                        acctbkSeqBean.setOpenId(parentBean.getOpenId());
                                        acctbkSeqBean.setType(1);
                                        acctbkSeqBean.setCreateDate(new Date());
                                        acctbkSeqBean.setMoney(goodsBean.getSpreadMoney());
                                        acctbkSeqBean.setRemark("粉丝购买商品：" + goodsBean.getGoodsName() + " 赠送佣金");
                                        acctbkSeqBeanMapper.insert(acctbkSeqBean);
                                    }
                                }
                            }
                        }
                    } else {
                        //开始计算普通分享佣金
                        UserBean parentBean = userBeanMapper.selectByOpenId(String.valueOf(parentIdObj));
                        if (null != parentBean) {
                            parentBean.setMoney(parentBean.getMoney() + goodsBean.getSpreadMoney());
                            userBeanMapper.updateByPrimaryKeySelective(parentBean);
                            redisService.del(String.format(Const.USER_REDIS_KEY, parentBean.getOpenId()));

                            AcctbkSeqBean acctbkSeqBean = new AcctbkSeqBean();
                            acctbkSeqBean.setChildId(userBean.getOpenId());
                            acctbkSeqBean.setOpenId(parentBean.getOpenId());
                            acctbkSeqBean.setType(1);
                            acctbkSeqBean.setCreateDate(new Date());
                            acctbkSeqBean.setMoney(goodsBean.getSpreadMoney());
                            acctbkSeqBean.setRemark("分享购买商品：" + goodsBean.getGoodsName() + " 赠送佣金");
                            acctbkSeqBeanMapper.insert(acctbkSeqBean);
                            redisService.hdel(key, orderBean.getOpenId());
                        }
                    }
                }
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public int updateAddressInfo(OrderSubmitParam orderSubmitParam, String openId) {
        UserBean userBean = userBeanMapper.selectByOpenId(openId);
        if (null == userBean) {
            throw new BusinessException("用户信息不正确");
        }
        if (userBean.getScore() < orderSubmitParam.getUserScore()) {
            throw new BusinessException("使用积分大于拥有的积分");
        }
        List<OrderBean> orderBeanList = orderBeanMapper.selectByOrderId(orderSubmitParam.getOrderSeq());
        if (CollectionUtils.isNotEmpty(orderBeanList)) {
            UserAddresBean userAddresBean = userAddresBeanMapper.selectByPrimaryKey(orderSubmitParam.getAddressId());
            int totalFee = 0;
            for (OrderBean c : orderBeanList) {
                c.setRemark(orderSubmitParam.getRemark());
                c.setUserName(userAddresBean.getUserName());
                c.setUserPhone(userAddresBean.getPhone());
                c.setUserAddress(userAddresBean.getProvince() + " " + userAddresBean.getCity() + " " + userAddresBean.getDistrict() + " " + userAddresBean.getDetail());
                c.setUserScore(orderSubmitParam.getUserScore());
                totalFee += c.getTotalPrice();
                orderBeanMapper.updateAddresById(c);
            }
            if (orderSubmitParam.getUserScore() * 10 > totalFee) {
                throw new BusinessException("使用积分大于商品总价");
            }
            if (orderSubmitParam.getUserScore() * 10 == totalFee) {//全部进行积分抵扣
                WechatRefundApiResult wechatRefundApiResult = new WechatRefundApiResult();
                wechatRefundApiResult.setOut_trade_no(orderSubmitParam.getOrderSeq());
                wechatRefundApiResult.setOpenid(openId);
                wechatRefundApiResult.setTotal_fee("0");
                payService.dealNotify(wechatRefundApiResult);
                return 2;//积分支付
            } else {
                return 1; //微信支付
            }
        }
        return 0;
    }

    @Transactional(rollbackFor = Exception.class)
    public String addCartOrder(String openId, CartParam cartParam) {
        String orderSeq = BusinessUtil.getOrderSeq(1);
        for (CartBean cartBean : cartParam.getList()) {
            CartBean returnBean = cartBeanMapper.selectByPrimaryKey(cartBean.getId());
            OrderBean orderBean = new OrderBean();
            orderBean.setOpenId(openId);
            orderBean.setStatus(1);
            orderBean.setOrderType(1);
            orderBean.setOrderId(orderSeq);
            orderBean.setGoodsId(returnBean.getGoodsId());
            orderBean.setGoodsAttr(returnBean.getGoodsAttr());
            orderBean.setTotalNum(cartBean.getAddNum());
            GoodsBean goodsBean = goodsBeanMapper.selectByPrimaryKey(orderBean.getGoodsId());
            if (null != goodsBean) {
                orderBean.setMerId(goodsBean.getMerId());
            } else {
                throw new BusinessException("商品已下架");
            }
            List<GoodsAttrValueBean> goodsAttrValueBeanList = goodsAttrValueBeanMapper.selectByByGoodsIdAndSuk(returnBean.getGoodsId(), returnBean.getGoodsAttr());
            UserBean userBean = userBeanMapper.selectByOpenId(openId);
            int totalPrice = 0;
            if (CollectionUtils.isEmpty(goodsAttrValueBeanList)) {
                log.error("【商品 goodsId = {} suk = {} 规格为空】", orderBean.getGoodsId(), orderBean.getGoodsAttr());
                if (goodsBean.getStock() <= 0) {
                    throw new BusinessException("商品" + goodsBean.getGoodsName() + "已售罄");
                }
                if (orderBean.getTotalNum() > goodsBean.getStock()) {
                    throw new BusinessException("商品" + goodsBean.getGoodsName() + "库存不足，只剩下：" + goodsBean.getStock() + "个");
                }
                if (null != userBean && userBean.getIsVip() == 1 && goodsBean.getVipPrice() != null) {
                    totalPrice = goodsBean.getVipPrice() * orderBean.getTotalNum();
                } else {
                    totalPrice = goodsBean.getPrice() * orderBean.getTotalNum();
                }
            } else {
                if (goodsAttrValueBeanList.get(0).getStock() <= 0) {
                    throw new BusinessException("商品" + goodsBean.getGoodsName() + "已售罄");
                }
                if (orderBean.getTotalNum() > goodsAttrValueBeanList.get(0).getStock()) {
                    throw new BusinessException("商品" + goodsBean.getGoodsName() + "库存不足，只剩下：" + goodsAttrValueBeanList.get(0).getStock() + "个");
                }
                if (null != userBean && userBean.getIsVip() == 1 && goodsBean.getVipPrice() != null) {
                    totalPrice = Integer.parseInt(goodsAttrValueBeanList.get(0).getVipPrice()) * orderBean.getTotalNum();
                } else {
                    totalPrice = Integer.parseInt(goodsAttrValueBeanList.get(0).getPrice()) * orderBean.getTotalNum();
                }
            }
            if (totalPrice <= 0) {
                throw new BusinessException("新增订单失败，商品价格不正确");
            }
            orderBean.setTotalPrice(totalPrice);
            orderBean.setCreateDate(new Date());
            orderBeanMapper.insert(orderBean);
            cartBeanMapper.deleteByPrimaryKey(cartBean.getId());
        }
        return orderSeq;
    }

    public String addSkillOrder(String openId, SeckillGoodsBean seckillGoodsBean) {
        SeckillGoodsBean returnBean = seckillGoodsBeanMapper.selectByPrimaryKey(seckillGoodsBean.getId());
        if (null == returnBean) {
            throw new BusinessException("当前秒杀不存在");
        }
        Date currentDate = new Date();
        if (returnBean.getStartTime().after(currentDate)) {
            throw new BusinessException("秒杀还未开始");
        }
        if (returnBean.getStopTime().before(currentDate)) {
            throw new BusinessException("秒杀已经结束");
        }
        if (seckillGoodsBean.getTotalNum() > returnBean.getNum()) {
            throw new BusinessException("购买商品数量大于限购数量：" + returnBean.getNum());
        }
        if (returnBean.getStock() <= 0) {
            throw new BusinessException("当前商品已售罄");
        }
        String orderSeq = BusinessUtil.getOrderSeq(1);
        OrderBean orderBean = new OrderBean();
        orderBean.setTotalNum(seckillGoodsBean.getTotalNum());
        orderBean.setTotalPrice(seckillGoodsBean.getTotalNum() * returnBean.getSeckillPrice());
        orderBean.setOrderId(orderSeq);
        //秒杀订单
        orderBean.setOrderType(2);
        orderBean.setCreateDate(new Date());
        orderBean.setOpenId(openId);
        orderBean.setStatus(1);
        orderBean.setGoodsAttr(seckillGoodsBean.getGoodsAttr());
        orderBean.setGoodsId(seckillGoodsBean.getGoodsId());
        GoodsBean goodsBean = goodsBeanMapper.selectByPrimaryKey(orderBean.getGoodsId());
        if (null != goodsBean) {
            orderBean.setMerId(goodsBean.getMerId());
        }
        orderBeanMapper.insert(orderBean);
        return orderSeq;
    }

    @Transactional(rollbackFor = Exception.class)
    public String addGroupOrder(String openId, GroupGoodsBean groupGoodsBean) {
        GroupGoodsBean returnBean = groupGoodsBeanMapper.selectByPrimaryKey(groupGoodsBean.getId());
        if (null == returnBean) {
            throw new BusinessException("当前拼团不存在");
        }
        Date currentDate = new Date();
        if (returnBean.getStartTime().after(currentDate)) {
            throw new BusinessException("拼团还未开始");
        }
        if (returnBean.getEndTime().before(currentDate)) {
            throw new BusinessException("拼团已经结束");
        }
        if (groupGoodsBean.getTotalNum() > returnBean.getNum()) {
            throw new BusinessException("购买商品数量大于限购数量：" + returnBean.getNum());
        }
        if (returnBean.getStock() <= 0) {
            throw new BusinessException("当前商品已售罄");
        }
        String orderSeq = BusinessUtil.getOrderSeq(1);
        OrderBean orderBean = new OrderBean();
        orderBean.setTotalNum(groupGoodsBean.getTotalNum());
        orderBean.setTotalPrice(groupGoodsBean.getTotalNum() * returnBean.getGroupPrice());
        orderBean.setOrderId(orderSeq);
        //拼团订单
        orderBean.setOrderType(3);
        orderBean.setCreateDate(new Date());
        orderBean.setOpenId(openId);
        orderBean.setStatus(1);
        orderBean.setGoodsAttr(groupGoodsBean.getGoodsAttr());
        orderBean.setGoodsId(groupGoodsBean.getGoodsId());
        GoodsBean goodsBean = goodsBeanMapper.selectByPrimaryKey(orderBean.getGoodsId());
        if (null != goodsBean) {
            orderBean.setMerId(goodsBean.getMerId());
        }
        orderBeanMapper.insert(orderBean);
        return orderSeq;
    }

    @Transactional(rollbackFor = Exception.class)
    public String addOrder(String openId, OrderBean orderBean) {
        orderBean.setCreateDate(new Date());
        orderBean.setOpenId(openId);
        orderBean.setStatus(1);
        orderBean.setOrderType(1);
        String orderSeq = BusinessUtil.getOrderSeq(1);
        orderBean.setOrderId(orderSeq);
        GoodsBean goodsBean = goodsBeanMapper.selectByPrimaryKey(orderBean.getGoodsId());
        if (null != goodsBean) {
            orderBean.setMerId(goodsBean.getMerId());
        } else {
            throw new BusinessException("当前商品已下架");
        }

        UserBean userBean = userBeanMapper.selectByOpenId(openId);
        List<GoodsAttrValueBean> goodsAttrValueBeanList = goodsAttrValueBeanMapper.selectByByGoodsIdAndSuk(orderBean.getGoodsId(), orderBean.getGoodsAttr());
        int totalPrice = 0;
        if (CollectionUtils.isEmpty(goodsAttrValueBeanList)) {
            log.error("【商品 goodsId = {} suk = {} 规格为空】", orderBean.getGoodsId(), orderBean.getGoodsAttr());
            if (goodsBean.getStock() <= 0) {
                throw new BusinessException("当前商品已售罄");
            }
            if (orderBean.getTotalNum() > goodsBean.getStock()) {
                throw new BusinessException("当前商品库存不足，只剩下：" + goodsBean.getStock() + "个");
            }
            if (null != userBean && userBean.getIsVip() == 1 && goodsBean.getVipPrice() != null) {
                totalPrice = goodsBean.getVipPrice() * orderBean.getTotalNum();
            } else {
                totalPrice = goodsBean.getPrice() * orderBean.getTotalNum();
            }
        } else {
            if (goodsAttrValueBeanList.get(0).getStock() <= 0) {
                throw new BusinessException("当前商品已售罄");
            }
            if (orderBean.getTotalNum() > goodsAttrValueBeanList.get(0).getStock()) {
                throw new BusinessException("当前商品库存不足，只剩下：" + goodsAttrValueBeanList.get(0).getStock() + "个");
            }
            if (null != userBean && userBean.getIsVip() == 1 && goodsBean.getVipPrice() != null) {
                totalPrice = Integer.parseInt(goodsAttrValueBeanList.get(0).getVipPrice()) * orderBean.getTotalNum();
            } else {
                totalPrice = Integer.parseInt(goodsAttrValueBeanList.get(0).getPrice()) * orderBean.getTotalNum();
            }
        }
        if (totalPrice <= 0) {
            throw new BusinessException("新增订单失败，商品价格不正确");
        }
        orderBean.setTotalPrice(totalPrice);
        orderBeanMapper.insert(orderBean);
        return orderSeq;
    }

    public List<OrderMergeBean> selectByOpenId(String openId, String status, ModelMap modelMap) {
        List<OrderBean> orderBeanList = orderBeanMapper.selectByOpenId(openId, Integer.parseInt(status));
        int totalMoney = 0;
        List<OrderMergeBean> orderMergeBeanList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(orderBeanList)) {
            Map<String, List<OrderBean>> mergeMap = orderBeanList.stream().collect(Collectors.groupingBy(OrderBean::getOrderId));
            for (Map.Entry<String, List<OrderBean>> entry : mergeMap.entrySet()) {
                List<OrderBean> valueList = entry.getValue();
                for (OrderBean orderBean : valueList) {
                    GoodsBean goodsBean = goodsBeanMapper.selectByPrimaryKey(orderBean.getGoodsId());
                    if (null != goodsBean) {
                        orderBean.setImage(goodsBean.getImage());
                        orderBean.setGoodsName(goodsBean.getGoodsName());
                    }
                    orderBean.setWebSinglePrice(BusinessUtil.getWebAmount(orderBean.getTotalPrice() / orderBean.getTotalNum()));
                }
                OrderMergeBean orderMergeBean = new OrderMergeBean();
                orderMergeBean.setOrderSeq(entry.getKey());
                orderMergeBean.setOrderType(valueList.get(0).getOrderType());
                orderMergeBean.setStatus(valueList.get(0).getStatus());
                orderMergeBean.setStatusName(BusinessUtil.getOrderStatusName(valueList.get(0).getStatus()));
                orderMergeBean.setTotalNum(entry.getValue().size());
                int sumMoney = entry.getValue().stream().mapToInt(OrderBean::getTotalPrice).sum();
                orderMergeBean.setWebTotalPrice(BusinessUtil.getWebAmount(sumMoney));
                orderMergeBean.setChangeDate(valueList.get(0).getUpdateDate() == null ? valueList.get(0).getCreateDate() : valueList.get(0).getUpdateDate());
                orderMergeBean.setCartInfo(entry.getValue());
                if(valueList.get(0).getOrderType() == 3 && !StringUtils.isEmpty(valueList.get(0).getGroupNum())){
                    //拼团订单
                    long groupNum = orderBeanMapper.countByGroupNum(valueList.get(0).getGroupNum());
                    orderMergeBean.setGroupNum((int) groupNum);
                }
                orderMergeBeanList.add(orderMergeBean);
                totalMoney += sumMoney;
            }
            Collections.sort(orderMergeBeanList, new Comparator<OrderMergeBean>() {
                @Override
                public int compare(OrderMergeBean o1, OrderMergeBean o2) {
                    return o2.getChangeDate().compareTo(o1.getChangeDate());
                }
            });
        }
        modelMap.put("totalOrder", orderMergeBeanList.size());
        modelMap.put("totalMoney", BusinessUtil.getWebAmount(totalMoney));

        List<Map<Integer, Integer>> staticMap = orderBeanMapper.groupByStatus(openId);
        Map<String, Integer> dataMap = new HashMap<>();
        dataMap.put("status1", 0);
        dataMap.put("status2", 0);
        dataMap.put("status3", 0);
        dataMap.put("status4", 0);
        dataMap.put("status5", 0);
        dataMap.put("status6", 0);
        if (CollectionUtils.isNotEmpty(staticMap)) {
            staticMap.stream().forEach(c -> {
                dataMap.put("status" + c.get("STATUS"), c.get("num"));
            });
        }
        modelMap.put("groupOrder", dataMap);
        return orderMergeBeanList;
    }

    public  List<Map<Integer, Integer>> groupByStatus(String openId){
        return orderBeanMapper.groupByStatus(openId);
    }

    public OrderBean selectSingleDetail(String id) {
        return orderBeanMapper.selectByPrimaryKey(Integer.parseInt(id));
    }

    public OrderBean selectDetail(String id) {
        OrderBean orderBean = orderBeanMapper.selectByPrimaryKey(Integer.parseInt(id));
        if (null != orderBean) {
            orderBean.setStatusName(BusinessUtil.getOrderStatusName(orderBean.getStatus()));
            orderBean.setWebSinglePrice(BusinessUtil.getWebAmount(orderBean.getTotalPrice() / orderBean.getTotalNum()));
            orderBean.setWebTotalPrice(BusinessUtil.getWebAmount(orderBean.getTotalPrice()));
            orderBean.setWebPayPrice(BusinessUtil.getWebAmount(orderBean.getPayPrice()));
            orderBean.setShouldPayDate(DateUtils.addDays(orderBean.getCreateDate(), 1));
            UserBean userBean = userBeanMapper.selectByOpenId(orderBean.getOpenId());
            if (null != userBean) {
                orderBean.setNickName(userBean.getNickName());
            }
            GoodsBean goodsBean = goodsBeanMapper.selectByPrimaryKey(orderBean.getGoodsId());
            if (null != goodsBean) {
                orderBean.setGoodsName(goodsBean.getGoodsName());
                orderBean.setImage(goodsBean.getImage());
            }
        }
        return orderBean;
    }

    public OrderMergeBean selectMergeDetail(String orderSeq) {
        List<OrderBean> orderBeanList = orderBeanMapper.selectByOrderId(orderSeq);
        OrderMergeBean orderMergeBean = new OrderMergeBean();
        if (CollectionUtils.isNotEmpty(orderBeanList)) {
            orderBeanList.stream().forEach(c -> {
                if (c.getPayPrice() == null) {
                    c.setPayPrice(0);
                }
                if (c.getTotalPrice() == null) {
                    c.setTotalPrice(0);
                }
                c.setWebSinglePrice(BusinessUtil.getWebAmount(c.getTotalPrice() / c.getTotalNum()));
                GoodsBean goodsBean = goodsBeanMapper.selectByPrimaryKey(c.getGoodsId());
                if (null != goodsBean) {
                    c.setGoodsName(goodsBean.getGoodsName());
                    c.setImage(goodsBean.getImage());
                }
            });
            orderMergeBean.setOrderSeq(orderSeq);
            orderMergeBean.setOrderType(orderBeanList.get(0).getOrderType());
            orderMergeBean.setStatus(orderBeanList.get(0).getStatus());
            orderMergeBean.setStatusName(BusinessUtil.getOrderStatusName(orderBeanList.get(0).getStatus()));
            orderMergeBean.setTotalNum(orderBeanList.size());
            int sumMoney = orderBeanList.stream().mapToInt(OrderBean::getTotalPrice).sum();
            orderMergeBean.setWebTotalPrice(BusinessUtil.getWebAmount(sumMoney));
            orderMergeBean.setChangeDate(orderBeanList.get(0).getUpdateDate() == null ? orderBeanList.get(0).getCreateDate() : orderBeanList.get(0).getUpdateDate());
            orderMergeBean.setPayType(orderBeanList.get(0).getPayType());
            orderMergeBean.setUseScore(orderBeanList.get(0).getUserScore());
            orderMergeBean.setWebPayPrice(BusinessUtil.getWebAmount(orderBeanList.get(0).getPayPrice()));
            orderMergeBean.setShouldPayDate(DateUtils.addDays(orderBeanList.get(0).getCreateDate(), 1));
            orderMergeBean.setCreateDate(orderBeanList.get(0).getCreateDate());
            orderMergeBean.setUserName(orderBeanList.get(0).getUserName());
            orderMergeBean.setUserPhone(orderBeanList.get(0).getUserPhone());
            orderMergeBean.setUserAddress(orderBeanList.get(0).getUserAddress());
            orderMergeBean.setCartInfo(orderBeanList);
        }
        return orderMergeBean;
    }

    public List<GoodsBean> selectOrderGoodsByOrderId(String orderId, ModelMap modelMap) {
        List<OrderBean> orderBeanList = orderBeanMapper.selectByOrderId(orderId);
        List<GoodsBean> returnList = new ArrayList<>();
        final int[] totalPrice = {0};
        final int[] totalNum = {0};
        if (CollectionUtils.isNotEmpty(orderBeanList)) {
            orderBeanList.stream().forEach(c -> {
                GoodsBean goodsBean = goodsBeanMapper.selectByPrimaryKey(c.getGoodsId());
                goodsBean.setGoodsAttr(c.getGoodsAttr());
                goodsBean.setAddNum(c.getTotalNum());
                goodsBean.setWebTotalPrice(BusinessUtil.getWebAmount(c.getTotalPrice()));
                goodsBean.setWebPrice(BusinessUtil.getWebAmount(c.getTotalPrice() / c.getTotalNum()));
                totalPrice[0] += c.getTotalPrice();
                totalNum[0] += c.getTotalNum();
                returnList.add(goodsBean);
            });
        }
        modelMap.put("totalPrice", BusinessUtil.getWebAmount(totalPrice[0]));
        modelMap.put("totalNum", totalNum[0]);
        return returnList;
    }

    public void updateStatus(int status, String orderSeq) {
        orderBeanMapper.updateStatusByOrderId(status, orderSeq);
    }

    public void updatePayPrice(int status, int payPrice, int id) {
        orderBeanMapper.updatePayPrice(status, payPrice, id);
    }

    public void updateGroupPayPrice(String groupNum, int status, int payPrice, int id) {
        orderBeanMapper.updateGroupPayPrice(groupNum, status, payPrice, id);
    }

    public void updateStatusByGroupNum(int status, String groupNum) {
        orderBeanMapper.updateStautsByGroupNum(status, groupNum);
    }

    public void updatePayTypeByOrderSeq(String orderSeq, int payType) {
        orderBeanMapper.updatePayTypeByOrderSeq(payType, orderSeq);
    }

    public void deleteOrder(String orderSeq) {
        orderBeanMapper.deleteByOrderId(orderSeq);
    }

    public List<OrderBean> selectByOrderId(String orderSeq) {
        return orderBeanMapper.selectByOrderId(orderSeq);
    }

    public JSONObject countByOpenId(String openId, String time) {
        List<OrderCount> countMap = orderBeanMapper.countByOpenId(openId, time);
        JSONObject jsonObject = new JSONObject();
        if (!CollectionUtils.isEmpty(countMap)) {
            for (OrderCount m : countMap) {
                String money = BusinessUtil.getWebAmount(m.getMoney());
                jsonObject.put("money", StringUtils.isEmpty(money) ? "0.0" : money);
                jsonObject.put("num", m.getNum());
                break;
            }
        }
        return jsonObject;
    }

    public Page listOrders(Page<OrderBean> pageInfo, OrderBean orderBean) {
        List<OrderBean> list = orderBeanMapper.listOrder(pageInfo, orderBean);
        if (CollectionUtils.isNotEmpty(list)) {
            list.stream().forEach(c -> {
                GoodsBean goodsBean = goodsBeanMapper.selectByPrimaryKey(c.getGoodsId());
                if (null != goodsBean) {
                    c.setGoodsName(goodsBean.getGoodsName());
                    c.setImage(goodsBean.getImage());
                    c.setWebSinglePrice(BusinessUtil.getWebAmount(c.getTotalPrice() / c.getTotalNum()));
                    c.setWebTotalPrice(BusinessUtil.getWebAmount(c.getTotalPrice()));
                    c.setWebPayPrice(BusinessUtil.getWebAmount(c.getPayPrice()));
                    c.setStatusName(BusinessUtil.getOrderStatusName(c.getStatus()));
                }
                UserBean userBean = userBeanMapper.selectByOpenId(c.getOpenId());
                if (null != userBean) {
                    c.setNickName(userBean.getNickName());
                }
            });
        }
        return pageInfo.setRecords(list);
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateOrderInfo(OrderBean orderBean) {
        OrderBean returnBean = orderBeanMapper.selectByPrimaryKey(orderBean.getId());
        if (null != returnBean) {
            if (orderBean.getStatus() == 5 && returnBean.getStatus() != 5) {
                //购买完成 计算佣金和积分
                finishOrder(returnBean.getOrderId());
            }
            if(orderBean.getStatus() == 3 && returnBean.getStatus() != 3){
                //已发货 发送一条提醒短信
                smsService.orderSendNotify(returnBean.getUserPhone(),returnBean.getOrderId());
            }
            returnBean.setStatus(orderBean.getStatus());
            returnBean.setTotalPrice(BusinessUtil.getDbAmount(orderBean.getWebTotalPrice()));
            returnBean.setPayPrice(BusinessUtil.getDbAmount(orderBean.getWebPayPrice()));
            orderBeanMapper.updateByPrimaryKey(returnBean);
        }
    }

    public void deleteOrders(String[] ids) {
        if (null != ids) {
            Arrays.stream(ids).forEach(c -> {
                orderBeanMapper.deleteByPrimaryKey(Integer.parseInt(c));
            });
        }
    }

    public JSONObject statisOrder(int userId) {
        List<OrderBean> orderBeanList = orderBeanMapper.statisOrders();
        JSONObject jsonObject = new JSONObject();
        int yestoday = 0;
        int sendingNum = 0;
        int totalMoney = 0;
        if (CollectionUtils.isNotEmpty(orderBeanList)) {
            for (OrderBean orderBean : orderBeanList) {
                if (orderBean.getStatus() == 2) {
                    sendingNum++;
                }
                if (BusinessUtil.isYesterday(orderBean.getCreateDate())) {
                    sendingNum++;
                }
                if(userId == 0 && orderBean.getStatus() > 1){
                    totalMoney += orderBean.getPayPrice();
                }else if(userId == orderBean.getMerId() && orderBean.getStatus() > 1){
                    totalMoney += orderBean.getPayPrice();
                }
            }
        }
        jsonObject.put("yestoday", yestoday);
        jsonObject.put("sendingNum", sendingNum);
        jsonObject.put("totalMoney", BusinessUtil.getWebAmount(totalMoney));
        return jsonObject;
    }
}
